using System.Text;
using System.Xml;

namespace Altova.Xml
{
	public class Document
	{
		public static XmlNode Load(string filename)
		{
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load(filename);
			return xmlDocument;
		}

		public static XmlNode Create()
		{
			return new XmlDocument();
		}

		public static void Save(TypeBase doc, string filename)
		{
			Save(doc, filename, "UTF-8", false, false);
		}

		public static void SetSchemaLocation(TypeBase node, string schLoc)
		{
			if (node.Node is XmlDocument)
			{
				XmlDocument xmlDocument = (XmlDocument)node.Node;
				XmlElement documentElement = xmlDocument.DocumentElement;
			}
			else
			{
				XmlElement xmlElement = (XmlElement)node.Node;
			}
		}

		public static void Save(TypeBase doc, string filename, string encoding)
		{
			Save(doc, filename, encoding, string.Compare(encoding, "UTF-16BE", true) == 0, string.Compare(encoding, "UTF-16", true) == 0);
		}

		public static void Save(TypeBase doc, string filename, string encoding, bool bBigEndian, bool bBOM)
		{
			XmlTextWriter xmlTextWriter = new XmlTextWriter(filename, GetEncodingObject(encoding, bBigEndian, bBOM));
			xmlTextWriter.Formatting = Formatting.Indented;
			XmlDocument xmlDocument = (XmlDocument)doc.Node;
			xmlDocument.Save(xmlTextWriter);
			xmlTextWriter.Close();
		}

		private static Encoding GetEncodingObject(string encoding, bool bBigEndian, bool bBOM)
		{
			switch (GetUnicodeSizeFromEncodingName(encoding))
			{
			case 1:
				return new UTF8Encoding(bBOM);
			case 2:
				return new UTF16Encoding(bBigEndian, bBOM);
			default:
				return Encoding.GetEncoding(encoding);
			}
		}

		private static int GetUnicodeSizeFromEncodingName(string encoding)
		{
			if (encoding == null)
			{
				return 0;
			}
			encoding = encoding.ToUpper();
			if (encoding.IndexOf("UTF-8") >= 0)
			{
				return 1;
			}
			if (encoding.IndexOf("UTF-16") >= 0 || encoding.IndexOf("UCS-2") >= 0)
			{
				return 2;
			}
			return 0;
		}
	}
}
